package info.techgeek.labs.javaSpecialists.curruptObjectState;

import java.util.concurrent.CountDownLatch;
import java.util.*;

public class TestCorruption {

	private static final int THREADS = 2;
	private static final CountDownLatch latch = new CountDownLatch(THREADS);
	private static final BankAccount heinz = new BankAccount(1000);

	public static void main(String[] args) {
		System.out.println("Start --------------");
		for (int i = 0; i < THREADS; i++) {
			System.out.println("Begin Thread "+i);
			addThread();
		}
		Timer timer = new Timer(true);
		timer.schedule(new TimerTask() {
			public void run() {
				try {
					System.out.println(heinz.getBalance());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, 100, 100);
	}

	private static void addThread() {
		System.out.println(" Inside addTherds ");
		
		new Thread() {
			{
				System.out.println("New Thread Start");
				start();
			}

			public void run() {
				System.out.println("run");
				latch.countDown();
				try {
					System.out.println(" Inside try ");
					latch.await();
				} catch (InterruptedException e) {
					return;
				}
				while (true) {
					try {
						heinz.deposit(100);
						heinz.withdraw(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		System.out.println(" End addTherds ");
	}
}
